package io.renren.config;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by tiantianli on 18/11/24.
 */
public class CorsInterceptor implements HandlerInterceptor{

        @Override
        public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception{

            // 如果是options请求直接放行
            if("OPTIONS".equals(httpServletRequest.getMethod())) {
                setJsonCross(httpServletRequest, httpServletResponse);
                return false;
            }

           setJsonCross(httpServletRequest, httpServletResponse);

            return true;
        }


        private void setJsonCross(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {

            String origin = httpServletRequest.getHeader("Origin");
            httpServletResponse.setHeader("Access-Control-Allow-Origin", origin);
            httpServletResponse.setHeader("Access-Control-Allow-Methods", origin);
            httpServletResponse.setHeader("Access-Control-Allow-Headers","Origin,Content-Type,Accept,token,X-Requested-With,userId");
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        }

        //其他postHandle,afterCompletion空继承


}
